﻿#ifndef JZNET_PACK_H_
#define JZNET_PACK_H_

#include <QByteArray>
#include <QDataStream>
#include <QMap>
#include <QVariant>
#include <QSharedPointer>
#include <QJsonObject>
using namespace std;

enum{
	NetPack_none = -1,
	NetPack_json,
	NetPack_fileOpReq,
    NetPack_fileOpRes,
    NetPack_fileDataReq,
    NetPack_fileDataRes,
	NetPack_user = 0x100,
};

class JZNetPack
{
public:
	JZNetPack();
	virtual ~JZNetPack();
	
    virtual int type() const = 0;
	virtual void saveToStream(QDataStream &s) const = 0;
	virtual void loadFromStream(QDataStream &s) = 0;

    int id() const;
	void setId(int seq);

private:
	int m_id;	
};
typedef QSharedPointer<JZNetPack> JZNetPackPtr;

class JZNetPackJson : public JZNetPack
{
public:
    JZNetPackJson();
    virtual ~JZNetPackJson();
		
    virtual int type() const;
	virtual void saveToStream(QDataStream &s) const;
	virtual void loadFromStream(QDataStream &s);	

	QJsonObject object;	
};

//JZNetPackManager
typedef JZNetPack *(*CreatePackFunc)();
class JZNetPackManager
{
public:
	static JZNetPackManager *instance();
	JZNetPackManager();

	void init();	
	void registPack(int type,CreatePackFunc func);
	JZNetPack *createPack(int id);

protected:
	QMap<int, CreatePackFunc> m_packFactory;	
};
template<class T> 
JZNetPack *JZNetPackCreate(){ return new T();}

void JZNetPackInit();
template<class T>
void JZNetRegistPack(int id)
{
    JZNetPackManager::instance()->registPack(id, JZNetPackCreate<T>);
}

#endif
